﻿using Consul;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace MyConsulClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            TestConsul();

        }

        static void TestConsul()
        {
            using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500")))
            {

                #region 1.获取所有登记在策的consul集合
                {
                    var services = consulClient.Agent.Services().Result.Response;
                    foreach (var service in services.Values)
                    {
                        Console.WriteLine($"id={service.ID},name={service.Service},ip={service.Address},port={service.Port} ");
                    }
                }
                #endregion

                #region 2.随机找一个登记在册的服务进行连接(客户端负载均衡-随机策略)
                {
                    var services = consulClient.Agent.Services().Result.Response.Values.Where(item => item.Service.Equals("MyConsulServiceOne", StringComparison.OrdinalIgnoreCase));
                    Random rand = new Random();
                    int index = rand.Next(services.Count());//[0,services.Count())
                    var s = services.ElementAt(index);
                    Console.WriteLine($"index={index},id={s.ID},service={s.Service},addr={s.Address},port={s.Port}");
                }

                #endregion

                #region 3.轮训策略(这里只是演示，实际要考虑并发和溢出的问题)
                {
                    Console.WriteLine(0 % 3);  //结果0
                    Console.WriteLine(1 % 3);  //结果1
                    Console.WriteLine(2 % 3);  //结果2
                    Console.WriteLine(3 % 3);  //结果1
                    Console.WriteLine(4 % 3);  //结果2

                    int Num = 0;
                    var services = consulClient.Agent.Services().Result.Response.Values.Where(item => item.Service.Equals("MyConsulServiceOne", StringComparison.OrdinalIgnoreCase));
                    for (int i = 1; i < 6; i++)
                    {
                        int index = Num++ % services.Count();
                        var s = services.ElementAt(index);
                        Console.WriteLine($"第{i}次的地址如下：");
                        Console.WriteLine($"index={index},id={s.ID},service={s.Service},addr={s.Address},port={s.Port}");
                    }
                }
                #endregion

                #region 4.接口测试
                {
                    var services = consulClient.Agent.Services().Result.Response.Values.Where(item => item.Service.Equals("MyConsulServiceOne", StringComparison.OrdinalIgnoreCase));
                    Random rand = new Random();
                    int index = rand.Next(services.Count());
                    var s = services.ElementAt(index);

                    var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();  //等价于以上三句话
                    IHttpClientFactory httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
                    string url2 = $"http://localhost:{s.Port}/api/testservice";
                    var client = httpClientFactory.CreateClient();
                    var content = new StringContent("serviceId="+s.ID, Encoding.UTF8, "application/x-www-form-urlencoded");
                    var response = client.GetAsync($"{url2}?serviceId={s.ID}").Result;
                    string result = "";
                    if (response.IsSuccessStatusCode)
                    {
                        result = response.Content.ReadAsStringAsync().Result;
                        Console.WriteLine(result);
                    }
                }
                #endregion

            }
            Console.ReadKey();
        } 
    }
}
